package com.lonwin.inspectionmanagement.mvp.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lonwin.inspectionmanagement.R;
import com.lonwin.inspectionmanagement.R2;
import com.lonwin.inspectionmanagement.app.utils.TimeUtils;
import com.lonwin.inspectionmanagement.di.component.DaggerNoSortOutRecordComponent;
import com.lonwin.inspectionmanagement.mvp.contract.NoSortOutRecordContract;
import com.lonwin.inspectionmanagement.mvp.model.api.Api;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.FilterBean;
import com.lonwin.inspectionmanagement.mvp.model.entity.bean.NoSortOutBean;
import com.lonwin.inspectionmanagement.mvp.presenter.NoSortOutRecordPresenter;
import com.lonwin.inspectionmanagement.mvp.ui.adapter.NoSortOutRecordAdapter;
import com.lonwin.inspectionmanagement.mvp.ui.adapter.TextAdapter;
import com.lonwin.inspectionmanagement.widget.ArrowDownUpView;
import com.lonwin.inspectionmanagement.widget.RecylerPopwindow;
import com.lonwin.inspectionmanagement.widget.dialog.LoadingDailog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/15/2018 13:57
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class NoSortOutRecordFragment extends BaseFragment<NoSortOutRecordPresenter> implements NoSortOutRecordContract.View , RecylerPopwindow.ShowListener,OnDateSetListener{


    @BindView(R2.id.river)
    ArrowDownUpView startriver;
    @BindView(R2.id.year)
    ArrowDownUpView endyear;
    @BindView(R2.id.ll_choice)
    LinearLayout llChoice;
    @BindView(R2.id.nosortout_record_RecyclerView)
    RecyclerView nosortoutRecordRecyclerView;
    @BindView(R2.id.commonaddress_refresh_layout)
    SmartRefreshLayout commonaddressRefreshLayout;
    @BindView(R2.id.vcover)
    View vcover;

    @BindView(R2.id.nosortout_record_startTime)
    TextView nosortout_record_startTime;
    @BindView(R2.id.nosortout_record_endTime)
    TextView nosortout_record_endTime;

    private NoSortOutRecordAdapter noSortOutRecordAdapter;

    private boolean isRefersh = false;
     int allpages=0;
     int pageIndex=1;
     private TimePickerDialog  mDialogAll;
    private LoadingDailog loadingDailog;
    public static NoSortOutRecordFragment newInstance() {
        NoSortOutRecordFragment fragment = new NoSortOutRecordFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerNoSortOutRecordComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_no_sort_out_record, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        commonaddressRefreshLayout.autoRefresh();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadingDailog=new LoadingDailog.Builder(getActivity()).setMessage("处理中...").create();
        nosortout_record_startTime.setText(TimeUtils.getFirstDayAndFirstMonth());
        nosortout_record_endTime.setText(TimeUtils.getNowDayAndMonth());
        initTime();
        setListener();

    }
public void initTime(){
      mDialogAll = new TimePickerDialog.Builder()
            .setCallBack(NoSortOutRecordFragment.this)
            .setCancelStringId("取消")
            .setSureStringId("确定")
            .setTitleStringId("选择查询时间")
                         .setYearText("年")
                         .setMonthText("月")
                         .setDayText("日")
//                         .setHourText("Hour")
//                         .setMinuteText("Minute")
            .setCyclic(false)
//            .setMinMillseconds(System.currentTimeMillis()-(100*365*24*60*60*1000))
//                         .setMaxMillseconds(System.currentTimeMillis()+10*1000 )
                         .setCurrentMillseconds(System.currentTimeMillis())
            .setThemeColor(getResources().getColor(R.color.color_FF098DDB))
            .setType(Type.YEAR_MONTH_DAY)
//                         .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
//                         .setWheelItemTextSelectorColor(getResources().getColor(R.color.timepicker_toolbar_bg))
            .setWheelItemTextSize(14)
            .build();
}
    private void setListener() {
        nosortoutRecordRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        noSortOutRecordAdapter=new NoSortOutRecordAdapter(new ArrayList<>());
        noSortOutRecordAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        nosortoutRecordRecyclerView.setAdapter(noSortOutRecordAdapter);
        commonaddressRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefersh = true;
                allpages=0;
                pageIndex=1;
                commonaddressRefreshLayout.finishRefresh(1500);
                mPresenter.getUndigestedXcjl(nosortout_record_startTime.getText().toString(),nosortout_record_endTime.getText().toString(),pageIndex);
            }
        });
        commonaddressRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefersh = false;
                if (allpages==pageIndex||allpages<pageIndex)
                {
                    ArmsUtils.makeText(getActivity(),"已经全部加载");
                    commonaddressRefreshLayout.finishLoadMore();
                    return;
                }
                pageIndex++;
                mPresenter.getUndigestedXcjl(nosortout_record_startTime.getText().toString(),nosortout_record_endTime.getText().toString(),pageIndex);
                commonaddressRefreshLayout.finishLoadMore(1000);

            }
        });
         nosortout_record_startTime.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 mDialogAll.show(getFragmentManager(),"开始时间");

             }
         });
         nosortout_record_endTime.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {

                 mDialogAll.show(getFragmentManager(),"结束时间");
             }
         });

    }
    private void initFirst() {
        List<FilterBean> yeardatas = new ArrayList<>();
        yeardatas.add(new FilterBean("2018年1月"));
        yeardatas.add(new FilterBean("2018年2月"));
        yeardatas.add(new FilterBean("2018年3月"));
        yeardatas.add(new FilterBean("2018年4月"));
        yeardatas.add(new FilterBean("2018年5月"));
        yeardatas.add(new FilterBean("2018年6月"));
        yeardatas.add(new FilterBean("2018年7月"));
        yeardatas.add(new FilterBean("2018年8月"));
        TextAdapter yearAdapter = new TextAdapter(yeardatas);
        RecylerPopwindow<TextAdapter> yearPopwindow = new RecylerPopwindow<TextAdapter>(yearAdapter, getActivity());
        yearPopwindow.setShowListener(this);
        yearPopwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                vcover.setVisibility(View.GONE);
                startriver.rotate180Arrow();
            }
        });
        yearAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (FilterBean item : yeardatas) {
                    item.setSelected(false);
                }
                yeardatas.get(position).setSelected(true);
                yearAdapter.notifyDataSetChanged();
                if (yearPopwindow.isShowing()) {
                    yearPopwindow.dismiss();
                }
                startriver.updateTitle(yeardatas.get(position).getTitle());
//                mPresenter.queryCruiseHistory(configBean.getAdcd(), "2018", String.valueOf(page), selectIndex == 0 ? null : String.valueOf(mdataBeans.get(selectIndex).getId().getGroupID()), false);
            }
        });
        startriver.setExpandListener(new ArrowDownUpView.ExpandListener() {
            @Override
            public void expand(View view) {
                yearPopwindow.showAsDropDown(llChoice);
            }

            @Override
            public void close(View view) {
                yearPopwindow.dismiss();
            }
        });
    }
    private void initSecond() {
        List<FilterBean> yeardatas = new ArrayList<>();
        yeardatas.add(new FilterBean("2018年1月"));
        yeardatas.add(new FilterBean("2018年2月"));
        yeardatas.add(new FilterBean("2018年3月"));
        yeardatas.add(new FilterBean("2018年4月"));
        yeardatas.add(new FilterBean("2018年5月"));
        yeardatas.add(new FilterBean("2018年6月"));
        yeardatas.add(new FilterBean("2018年7月"));
        yeardatas.add(new FilterBean("2018年8月"));
        TextAdapter yearAdapter = new TextAdapter(yeardatas);
        RecylerPopwindow<TextAdapter> yearPopwindow = new RecylerPopwindow<TextAdapter>(yearAdapter, getActivity());
        yearPopwindow.setShowListener(this);
        yearPopwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                vcover.setVisibility(View.GONE);
                endyear.rotate180Arrow();
            }
        });
        yearAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (FilterBean item : yeardatas) {
                    item.setSelected(false);
                }
                yeardatas.get(position).setSelected(true);
                yearAdapter.notifyDataSetChanged();
                if (yearPopwindow.isShowing()) {
                    yearPopwindow.dismiss();
                }
                startriver.updateTitle(yeardatas.get(position).getTitle());
//                mPresenter.queryCruiseHistory(configBean.getAdcd(), "2018", String.valueOf(page), selectIndex == 0 ? null : String.valueOf(mdataBeans.get(selectIndex).getId().getGroupID()), false);
            }
        });
        endyear.setExpandListener(new ArrowDownUpView.ExpandListener() {
            @Override
            public void expand(View view) {
                yearPopwindow.showAsDropDown(llChoice);
            }

            @Override
            public void close(View view) {
                yearPopwindow.dismiss();
            }
        });
    }
    /**
     * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法,
     * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)}
     * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用
     * <p>
     * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行
     * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的
     * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了
     * <p>
     * Example usage:
     * <pre>
     * public void setData(@Nullable Object data) {
     *     if (data != null && data instanceof Message) {
     *         switch (((Message) data).what) {
     *             case 0:
     *                 loadData(((Message) data).arg1);
     *                 break;
     *             case 1:
     *                 refreshUI();
     *                 break;
     *             default:
     *                 //do something
     *                 break;
     *         }
     *     }
     * }
     *
     * // call setData(Object):
     * Message data = new Message();
     * data.what = 0;
     * data.arg1 = 1;
     * fragment.setData(data);
     * </pre>
     *
     * @param data 当不需要参数时 {@code data} 可以为 {@code null}
     */
    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
    loadingDailog.show();
    }

    @Override
    public void hideLoading() {
        loadingDailog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);

        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void getUndigestedXcjlSuccess(List<NoSortOutBean.DataBean.RecordsBean> dataBeans,int mallPage) {

       this.allpages=mallPage;
        if (dataBeans==null||dataBeans.isEmpty())
        {
            noSortOutRecordAdapter.setEmptyView(ArmsUtils.inflate(getActivity(),R.layout.empty_view));
        }
        if (isRefersh)
      {
          //没有数据,需要处理
          noSortOutRecordAdapter.setNewData(dataBeans);
          commonaddressRefreshLayout.finishRefresh();
      }else {
          noSortOutRecordAdapter.addData(dataBeans);
            commonaddressRefreshLayout.finishLoadMore(500);
      }
    }

    @Override
    public Activity getMyActivity() {
        return getActivity();
    }

    @Override
    public void show() {
        vcover.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        timePickerView.dismiss();
        if (timePickerView.getTag().equals("开始时间"))
        {
            nosortout_record_startTime.setText(TimeUtils.longToStrTime(millseconds));

        } else {
           nosortout_record_endTime.setText(TimeUtils.longToStrTime(millseconds));
        }
        if (nosortout_record_startTime.getText().toString().compareTo(nosortout_record_endTime.getText().toString())<0)
        {
            commonaddressRefreshLayout.autoRefresh();
            return;
        }
        showMessage("开始时间不能大于结束时间");
    }
}
